//
//  BaseHttpRequest.m
//  didacar
//
//  Created by 度周末网络-王腾 on 15/11/20.
//  Copyright © 2015年 dzmmac. All rights reserved.
//

#import "BaseHttpRequest.h"
#import "KDateFormatter.h"
#import "UIDevice+IdentifierAddition.h"
#import "SVProgressHUD.h"
#import "NSDictionary+SafeAccess.h"
@interface BaseHttpRequest ()

@property (nonatomic, strong) AFHTTPRequestOperationManager *jsonManager;

@property (nonatomic, strong) AFHTTPRequestOperationManager *httpManager;

@end

@implementation BaseHttpRequest
+ (BaseHttpRequest *)sharedInstance{
    static BaseHttpRequest *singleton;
    static dispatch_once_t token;
    dispatch_once(&token,^{
        singleton = [[BaseHttpRequest alloc]init];
    });
    return singleton;
}

- (id)init{
    if (self = [super init]) {
        [self configManager];
    }
    return self;
}

-(void)configManager{
    _jsonManager = [AFHTTPRequestOperationManager manager];
    _jsonManager.requestSerializer  = [AFJSONRequestSerializer serializer];
    _jsonManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _jsonManager.requestSerializer.timeoutInterval = 10;
    
    _httpManager = [AFHTTPRequestOperationManager manager];
    _httpManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    _httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _httpManager.requestSerializer.timeoutInterval = 10;
}

-(void)requestCanelOne{
    [[[[self.jsonManager operationQueue] operations] lastObject] cancel];
}

-(void)requestCanelAll{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [[self.jsonManager operationQueue] cancelAllOperations];
}

/**
 *  POST方式请求数据
 *
 *  @param actionName    POST 接口名称
 *  @param requestEntity 请求的参数:接受继承于jastor的对象以及字典对象
 *  @param alertMessage  是否有提示框出现  nil  不出现
 *  @param successBlock  成功回掉
 *  @param errorBlock    失败回掉
 */
- (void)sendRequestToPost:(NSString*)actionName
                 withData:(id) requestEntity
             alertMessage:(NSString *)alertMessage
                  success:(void (^)(NSDictionary *dicData)) successBlock
                    error:(void (^)(NSString *errorMsg)) errorBlock{
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    if (alertMessage) {
        [SVProgressHUD show];
    }
    
    // 获取post数据
    NSMutableDictionary *postData = [self getPostDataWithActionName:actionName withData:requestEntity];
  
//    NSLog([NSString stringWithFormat:@"request...%@",[postData JSONString]]);
    typeof(self) __weak weakSelf = self;
    [self.jsonManager POST:ServerDomain parameters:postData success:^(AFHTTPRequestOperation *operation, id responseObject) {
    
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSString *responseString = [[NSString alloc] initWithData: responseObject
                                                         encoding: NSUTF8StringEncoding];
        NSDictionary *dic = [responseString objectFromJSONString];
        
        NSString *code = [dic objectForKey:@"Code"];
        
        if ([code isEqualToString:@"1"]) {
            
            if (alertMessage) {
                [SVProgressHUD dismiss];
            }
            successBlock(dic);
        }else{
            errorBlock([dic objectForKey:@"Message"]);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
   
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        [weakSelf requestError:error errorBlock:errorBlock];
        
    }];
}

-(void)requestError:(NSError *)error errorBlock:(void (^)(NSString *errorMsg)) errorBlock{

    // 访问被限制
    if (error.code == -1005) {
        errorBlock(nil);
    }
    // 请求被中断
    else if(error.code == -999) {
        
    }
    // 请求超时
    else if (error.code == -1001){
        errorBlock(@"请求超时");
    }
    // 没有网络
    else if (error.code == -1009){
        errorBlock(@"网络连接失败！请检查网络");
    }
    else{
        errorBlock(error.localizedDescription);
    }
}

/**
 *  Get方式请求数据
 *
 *  @param strUrl       URL
 *  @param successBlock 成功回掉
 *  @param errorBlock   失败回掉
 */
-(void)dataGetHttpRequestWithUrl:(NSString*)strUrl
                         success:(void (^)(NSString *stringData)) successBlock
                           error:(void (^)(NSString *errorMsg)) errorBlock{
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self.httpManager GET:strUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSString *responseString = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding];
        successBlock(responseString);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        errorBlock(@(operation.response.statusCode).stringValue);
    }];
}

/**
 *  @author Jakey
 *
 *  @brief  下载文件
 *
 *  @param paramDic   附加post参数
 *  @param requestURL 请求地址
 *  @param savedPath  保存 在磁盘的位置
 *  @param success    下载成功回调
 *  @param failure    下载失败回调
 *  @param progress   实时下载进度回调
 */
- (void)downloadFileWithOption:(NSDictionary *)paramDic
                 withInferface:(NSString*)requestURL
                     savedPath:(NSString*)savedPath
               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *errorMsg))failure
                      progress:(void (^)(float progress))progress

{
    
    //沙盒路径    //NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:requestURL parameters:paramDic error:nil];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float p = (float)totalBytesRead / totalBytesExpectedToRead;
        progress(p);
        NSLog(@"download：%f", (float)totalBytesRead / totalBytesExpectedToRead);
        
    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation,responseObject);
        NSLog(@"下载成功");
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        success(operation,error);
        
        NSLog(@"下载失败");
        
    }];
    
    [operation start];
}


-(NSMutableDictionary *)getPostDataWithActionName:(NSString *)actionName withData:(id)requestEntity
{
    NSMutableDictionary *actionBody = nil;
    if ([requestEntity isKindOfClass:[NSDictionary class]]) {
        actionBody = [NSMutableDictionary dictionaryWithDictionary:requestEntity];
    }else{
        actionBody = [requestEntity toDictionary];
    }
    if (actionBody == nil) {
        actionBody = [[NSMutableDictionary alloc ] init];
    }
    
    NSMutableDictionary *postBody = [[NSMutableDictionary alloc] init];
    
    // 具体的请求参数
    [postBody setObj:[actionBody JSONString] forKey:@"Param"];
    [postBody setObj:App_Version  forKey:@"Version"];
    [postBody setObj:@"iphone"    forKey:@"Plat"];
    [postBody setObj:actionName   forKey:@"Method"];
    
    [postBody setObj:[UIDevice currentDevice].identifierForVendor.UUIDString forKey:@"DeviceID"];
    [postBody setObj:[UIDevice getIdfa]   forKey:@"Idfa"];
    [postBody setObj:[[NSBundle mainBundle] bundleIdentifier] forKey:@"BundleId"];
    
    //  时间搓
    NSString *timestemp = [KDateFormatter dateToStringDate:[NSDate date] formatString:KDateFormatterStyle1];
    [postBody setObj:timestemp  forKey:@"TS"];
    
    // 加密
    NSString *sha1Result=[[[NSString stringWithFormat:@"%@%@",[[actionBody JSONString] lowercaseString],timestemp] md5] lowercaseString];
    
    NSString *sha2Result = [NSString stringWithFormat:@"%@%@",[actionName lowercaseString],App_Account];
    
    NSString *sha1DesResult = [[[NSString stringWithFormat:@"%@%@",sha1Result,sha2Result] md5] lowercaseString];
    
    // token
    [postBody setObj:sha1DesResult forKey:@"Token"];
    
    return postBody;
}



@end
